package com.bxs.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
    ServerSocket serverSocket = null;
    public SocketServer() throws IOException {
        serverSocket = new ServerSocket(9999);
    }


    public void start() throws IOException {
        //监听
        Socket socket = null;
        System.out.println("server start listening");
        while((socket = serverSocket.accept()) != null){
            System.out.println("accept...");
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer sb = new StringBuffer();
            char buf[] = new char[1024];
            int len = 0;
            sb.append(bufferedReader.read(buf, 0, 1024));
            System.out.println("server receive: " + sb);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
            bw.write("server response");
            bw.close();
            bufferedReader.close();
            outputStream.close();
            inputStream.close();
            socket.close();
        }

    }

    public static void main(String[] args) throws IOException {
        SocketServer socketServer = new SocketServer();
        socketServer.start();
    }
}
